﻿/**
 *@description:
 *@file: text_render.cpp
 *@author: snow-tyan
 *@email: zziywang@163.com
 *@date: 30 January 2023
 *@copyright: 2018-2022 AiRiA. All rights reserved.
 */

// clang-format off
#include "mygl/util.h"
#include "mygl/es_image.h"
#include "mygl/shader.h"

#include <cmath>
#include <iostream>
#include <map>
#include <memory>

#include <glad/glad.h>   // 管理OpenGL的函数指针
#include <GLFW/glfw3.h>  // 提供窗口和OpenGL context

#include <freetype2/ft2build.h>
#include FT_FREETYPE_H
// clang-format on

#ifndef PROJECT_ROOT
#define PROJECT_ROOT "/home/snow/OpenGLESProjects/MyOpenGLES_glfw"
#endif

using namespace mygl;

const std::string kProjectRoot = PROJECT_ROOT + std::string("/");
const std::string kWorkSpaceRoot = kProjectRoot + "07-InPractice/01-TextRendering/";
const std::string kShaderRoot = kWorkSpaceRoot + "text_render/";
const std::string kResourcesRoot = kProjectRoot + "resources/fonts/";
const unsigned int kWindowWidth = 800;
const unsigned int kWindowHeight = 600;
const char *kWindowName = "TextRendering";

/// Holds all state information relevant to a character as loaded using FreeType
struct Character {
  GLuint TextureID;    // ID handle of the glyph texture
  glm::ivec2 Size;     // Size of glyph
  glm::ivec2 Bearing;  // Offset from baseline to left/top of glyph
  GLuint Advance;      // Horizontal offset to advance to next glyph
};
std::map<GLchar, Character> Characters;

GLuint VAO, VBO;

void RenderText(std::shared_ptr<Shader> &shader, std::string text, GLfloat x, GLfloat y,
                GLfloat scale, glm::vec3 color);

std::shared_ptr<Shader> ShaderInit() {
  std::string vertex_path = kShaderRoot + "shader.vs";
  std::string fragment_path = kShaderRoot + "shader.fs";
  auto shader = std::make_shared<Shader>(vertex_path, fragment_path);
  CHECK_MSG(shader->Init() == 0, "Shader Init Failed");
  return shader;
}

std::shared_ptr<EsImage> LoadImage(const std::string &pic_name) {
  std::string picture = kResourcesRoot + pic_name;
  std::cout << picture << std::endl;
  auto es_image = std::make_shared<EsImage>();
  CHECK_MSG(es_image->LoadImage(picture) == 0, "Load Image Failed");
  es_image->PrintLoadTime();
  es_image->PrintImageInfo();
  return es_image;
}

void PrintGlmVector(const glm::vec3 &vec) {
  printf("vec(%.1f, %.1f, %.1f)\n", vec.x, vec.y, vec.z);
}

glm::mat4 TransformTest() {
  glm::vec4 vec(1.0f, 0.0f, 0.0f, 1.0f);  // x轴的单位向量，仅用于测试
  PrintGlmVector(vec);
  glm::mat4 trans(1.0f);  // 初始化默认是零矩阵
  trans = glm::translate(trans, glm::vec3(0.1f, 0.1f, 0.1f));  // 位移
  PrintGlmVector(trans * vec);
  trans = glm::rotate(trans, glm::radians(90.0f),
                      glm::vec3(0.0f, 0.0f, 1.0f));  // 沿z轴逆时针旋转90度
  PrintGlmVector(trans * vec);
  trans = glm::scale(trans, glm::vec3(0.5f, 0.5f, 1.0f));  // 缩放
  PrintGlmVector(trans * vec);
  return trans;
}

int main() {
  // glfw: initialize and configure
  // ------------------------------
  glfwInit();
  // OpenGL 3.3
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 核心模式

  // glfw window creation
  // --------------------
  GLFWwindow *window =
      glfwCreateWindow(kWindowWidth, kWindowHeight, kWindowName, NULL, NULL);
  if (window == NULL) {
    std::cout << "Failed to create GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }
  glfwMakeContextCurrent(window);

  // glad: load all OpenGL function pointers
  // ---------------------------------------
  if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    std::cout << "Failed to initialize GLAD" << std::endl;
    return -1;
  }
  // print: gl info
  printf("GL_VENDOR: %s\n", glGetString(GL_VENDOR));  // 打印gl供应商
  printf("GL_VERSION: %s\n", glGetString(GL_VERSION));  // 打印gl版本，确定使用gles3
  // printf("%s\n", glGetString(GL_EXTENSIONS));  // 打印GL_EXTENSIONS
  int max_attributes;
  glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_attributes);  // 硬件支持的最大顶点属性数量
  printf("Max number of vertex attribute supported: %d\n", max_attributes);

  //// Initialize GLEW to setup the OpenGL Function pointers
  // glewExperimental = GL_TRUE;
  // glewInit();

  // Define the viewport dimensions
  glViewport(0, 0, kWindowWidth, kWindowHeight);

  // Set OpenGL options
  glEnable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  // build and compile our shader zprogram
  // ------------------------------------
  auto shader = ShaderInit();
  glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(kWindowWidth), 0.0f,
                                    static_cast<GLfloat>(kWindowHeight));
  shader->UseProgram();
  shader->SetUniformMat4Float("projection", projection);
  shader->SetUniformInt("text", 0);

  // FreeType
  FT_Library ft;
  // All functions return a value different than 0 whenever an error occurred
  if (FT_Init_FreeType(&ft)) {
    std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl;
  }

  // Load font as face
  FT_Face face;
  if (FT_New_Face(ft, std::string(kResourcesRoot + "Antonio-Regular.ttf").c_str(), 0,
                  &face)) {
    std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl;
  }

  // Set size to load glyphs as
  FT_Set_Pixel_Sizes(face, 0, 48);

  // Disable byte-alignment restriction
  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

  // Load first 128 characters of ASCII set
  for (GLubyte c = 0; c < 128; c++) {
    // Load character glyph
    if (FT_Load_Char(face, c, FT_LOAD_RENDER)) {
      std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl;
      continue;
    }
    if (face->glyph->bitmap.buffer) {
      printf("c=%d, width=%d, height=%d, buffer=%d\n", c, face->glyph->bitmap.width,
             face->glyph->bitmap.rows, face->glyph->bitmap.buffer[0]);
    }
    // Generate texture
    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, face->glyph->bitmap.width,
                 face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE,
                 face->glyph->bitmap.buffer);
    // Set texture options
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Now store character for later use
    Character character = {
        texture, glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
        glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
        face->glyph->advance.x};
    Characters.insert(std::pair<GLchar, Character>(c, character));
  }
  glBindTexture(GL_TEXTURE_2D, 0);
  // Destroy FreeType once we're finished
  FT_Done_Face(face);
  FT_Done_FreeType(ft);

  // Configure VAO/VBO for texture quads
  glGenVertexArrays(1, &VAO);
  glGenBuffers(1, &VBO);
  glBindVertexArray(VAO);
  glBindBuffer(GL_ARRAY_BUFFER, VBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindVertexArray(0);

  // Game loop
  while (!glfwWindowShouldClose(window)) {
    // Check and call events
    glfwPollEvents();

    // Clear the colorbuffer
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    RenderText(shader, "This is sample text", 25.0f, 25.0f, 1.0f,
               glm::vec3(0.5, 0.8f, 0.2f));
    RenderText(shader, "(C) LearnOpenGL.com", 540.0f, 570.0f, 0.5f,
               glm::vec3(0.3, 0.7f, 0.9f));

    // Swap the buffers
    glfwSwapBuffers(window);
  }

  glfwTerminate();
  return 0;
}

void RenderText(std::shared_ptr<Shader> &shader, std::string text, GLfloat x, GLfloat y,
                GLfloat scale, glm::vec3 color) {
  // Activate corresponding render state
  shader->UseProgram();
  shader->SetUniformVecnFloat("textColor", 3, {color.x, color.y, color.z});
  glActiveTexture(GL_TEXTURE0);
  glBindVertexArray(VAO);

  // Iterate through all characters
  std::string::const_iterator c;
  for (c = text.begin(); c != text.end(); c++) {
    Character ch = Characters[*c];

    GLfloat xpos = x + ch.Bearing.x * scale;
    GLfloat ypos = y - (ch.Size.y - ch.Bearing.y) * scale;

    GLfloat w = ch.Size.x * scale;
    GLfloat h = ch.Size.y * scale;
    // Update VBO for each character
    GLfloat vertices[6][4] = {{xpos, ypos + h, 0.0, 0.0},    {xpos, ypos, 0.0, 1.0},
                              {xpos + w, ypos, 1.0, 1.0},

                              {xpos, ypos + h, 0.0, 0.0},    {xpos + w, ypos, 1.0, 1.0},
                              {xpos + w, ypos + h, 1.0, 0.0}};
    // Render glyph texture over quad
    glBindTexture(GL_TEXTURE_2D, ch.TextureID);
    // Update content of VBO memory
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices),
                    vertices);  // Be sure to use glBufferSubData and not glBufferData
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    // Render quad
    glDrawArrays(GL_TRIANGLES, 0, 6);
    // Now advance cursors for next glyph (note that advance is number of 1/64 pixels)
    x += (ch.Advance >> 6) *
         scale;  // Bitshift by 6 to get value in pixels (2^6 = 64 (divide amount of
                 // 1/64th pixels by 64 to get amount of pixels))
  }
  glBindVertexArray(0);
  glBindTexture(GL_TEXTURE_2D, 0);
}